import {type Request, Response, Express} from "express";
import { wafSession, type Proxy } from "../endpoints/wafSession.js";
import * as response from "../response/response.js";
import {Base} from "../response/response.js";

interface ReqWAFSession {
    url: string;
    proxy?: Proxy;
}

let active = 0;

function httpWAFSession(req: Request<{}, {}, ReqWAFSession>, res :Response)  {
    if (active >= global.maxConcurrency) {
        res.status(200).json(<Base<null>>{ code: 429, msg: 'Too Many Requests' })
        return
    }
    active++
    wafSession(req.body.url, req.body.proxy).then(ret => {
        response.successWithData(res, ret)
    }).catch(e => {
        if (e instanceof Error) {
            response.internalErrorWithMsg(res, e.message);
        } else if (typeof(e) == 'string') {
            response.internalErrorWithMsg(res, e);
        } else {
            console.error('不确定的错误', e);
        }
    }).finally(() => {
        active--
    })
}

function health(_: Request, res :Response) {
    response.successWithData(res, null)
}

export function router(app: Express) {
    app.get('/health', health)
    app.post('/wafSession', httpWAFSession)
}
